/**
 * 扩展一个qsform模块
 * 憩石自定义的表单转json模块
 */      

layui.define(function(exports) { //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
	$ = layui.jquery;
	var obj = {
		getDataByQsName : function(data) {
			let dataStr = "", _form = data.form;
	    	for(let i=0;i<_form.length; i++){
	    		let ele = _form[i];
	    		let qsNameAttr = ele.attributes["qs-name"];
	    		// 没有qs-name属性的表单元素，跳过
				if(qsNameAttr == undefined || qsNameAttr == ""){
					continue;
				}
	    		let qsNameVal = ele.attributes["qs-name"].value;
	    		let val = ele.value;
	    		if(val != undefined && val != ""){
	    			val = val.toString().replace(/\"/g, "\\\"");
	    			dataStr += ("\""+qsNameVal + "\":\"" + val + "\",");
	    		}
	    	}
	    	
	    	return "{" + obj.cutLastOne(dataStr) + "}";
		},
		setDataByQsName : function(body, obj){
			let fromObj = body[0].firstElementChild;
			let eles = fromObj.elements;
			for(let i = 0; i < eles.length; i++){
				let ele = eles[i];
				let qsNameAttr = ele.attributes["qs-name"];
				// 没有qs-name属性的表单元素，跳过
				if(qsNameAttr == undefined || qsNameAttr == ""){
					continue;
				}
				let qsNameVal = ele.attributes["qs-name"].value;
				if(qsNameVal != null){
					body.find("."+qsNameVal).val(obj[qsNameVal]);
				}

				let qsRelyAttr = ele.attributes["qs-rely"];
				// qs-rely属性不为空的表单元素，则说明其他有关联的表单元素
				if(qsRelyAttr != undefined && qsRelyAttr != ""){
					let qsRelyVal = ele.attributes["qs-rely"].value;
					if(qsRelyVal == 'switch'){
						let qsRelyYesVal = 1;
						if(ele.attributes["qs-rely-yes"] != undefined){
							qsRelyYesVal = ele.attributes["qs-rely-yes"].value;
						}
						// 组织关联的表单元素
						if(qsRelyYesVal == obj[qsNameVal]){
							body.find("input[type='checkbox'][lay-filter='"+qsNameVal+"']").attr("checked", "checked");
						}
					}
				}
			}
		},
		cutLastOne : function(str)	{
			if(str != null && (typeof(str) == "string" && str.length > 1)){
	    		return str.substring(0, str.length-1);
	    	}
	    	return str;
		}
	};

	//输出qsform接口
	exports('qsform', obj);
});